<?php
namespace control;

// 配件管理
use JetBrains\PhpStorm\NoReturn;

class partsClass extends adIndexClass
{
	private const page        = 'parts';
	private const table       = 'parts';
	private const tableRecord = 'parts_inventory_record';
	private const title       = '配件管理';
	private const state       = ['启用', '停用'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'type'          => [
                        'name'  => "类别",
                        'width' => 200,
                    ],
                    'code'  => [
                        'name'  => '编码',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'name'         => [
                        'name'  => '配件名称',
                        'width' => 200,
                    ],
                    'model'          => [
                        'name'  => '规格',
                        'width' => 150,
                    ],
                    'unit'          => [
                        'name'  => '计量单位',
                        'width' => 150,
                    ],
                    'inventoryNum'          => [
                        'name'  => '数量',
                        'width' => 150,
                    ],
                    'unitPrice'          => [
                        'name'  => '单价（'. static::$unit . '）',
                        'width' => 150,
                    ],
                    'money'          => [
                        'name'  => '金额（'. static::$unit . '）',
                        'width' => 150,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 150,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "编码" => text(array("name" => "code")),
                    "类别"   => select(["name" => "type", 'option' => explode('，', para(self::page . 'Type'))]),
                    "配件名称" => text(array("name" => "name")),
                ],
                [
                    "规格" => text(array("name" => "model")),
                    "状态" => select(["name" => "state", 'option' => self::state]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

	/**
	 * 列表-查询条件
	 *
	 * @return string
	 */
	public function home(): string
	{
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('".self::page."','edit')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        if ($this->power(self::page, "state")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get['cla']}', 'operate', {'act': 'changeState', 'state': '启用'})\">启用</span>\n";
        }
        if ($this->power(self::page, "state")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get['cla']}', 'operate', {'act': 'changeState', 'state': '停用'})\">停用</span>\n";
        }
        if ($this->power(self::page, 'import')) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','importFrame',{cla:'".self::page."'})\">导入</span>";
        }
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
	}

	/**
	 * 客户列表-查询结果
	 *
	 * @return bool|string
	 */
	public function homeSearch(): string
	{
		//查询结果
		$equal = [
			'type'  => $this->post('type'),
			'state' => $this->post('state'),
			'coid'  => self::$coid,
		];
		$like  = [
			'code'  => $this->post('code'),
			'name'  => $this->post('name'),
			'model' => $this->post('model'),
		];
		//生成查询语句
		$where                       = search([
			"="    => $equal,
			"like" => $like,
		]);
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
		$page                        = $this->page([
			"table" => self::table,
			"where" => " 1=1 " . $where,
			"order" => $orderBy['orderBy'],
		]);
		$_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
		//获取记录
		$url = root . "control/adIndex.html?cla=" . self::page;
		foreach ($page['array'] as $array) {
			//列表控件
			$dominate     = [
				"box"    => ["name" => "listId", "value" => $array['id']],
				"detail" => ["title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"],
				"edit"   => ["title" => "编辑", "click" => "layer('" . self::page . "','edit',{id:'" . $array['id'] . "'})"],
			];
			$inventoryNum = self::inventoryNum($array['id']);
			$unitPrice    = self::unitPrice($array['id']);
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'inventoryNum':
                        $row[] = self::lostZero($inventoryNum,'numPrecision');
                        break;
                    case 'unitPrice':
                        $row[] = self::lostZero($unitPrice,'pricePrecision');
                        break;
                    case 'money':
                        $row[] = self::formattingFigure($unitPrice * $inventoryNum);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
		}
        $totalQuery = find([
            'table'  => "parts_inventory_record",
            'single' => " coid = '".self::$coid."' and partsId in (select id from ".self::table." where 1=1 {$where}) ",
            'field'  => "ifnull(sum(num),0) as num",
        ]);
        $totalQuery = find([
            'table'  => "parts_inventory_record",
            'single' => " coid = '".self::$coid."' and partsId in (select id from ".self::table." where 1=1 {$where}) ",
            'field'  => "ifnull(sum(num),0) as num",
        ]);
        $total    = [
            'inventoryNum'        => self::lostZero($totalQuery['num'], 'numPrecision'),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
		//返回
		$json['html'] = $page['hint'] . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
		return json_encode($json, 320);
	}

	/**
	 * 设备 - 配件
	 *
	 * @return bool|string
	 */
	public function parts(): string
	{
		//生成查询语句
		$where = search([
			"=" => [
				'coid' => self::$coid,
				'eqid' => $this->get('id'),
			],
		]);
		$page  = $this->page(["table" => 'equipment_part', "where" => $where, "order" => "time desc"]);
		//获取表头
		$tr[] = ['操作', '配件编码', '配件名称', '厂家', '规格型号', '单位', '数量', '备注'];
		//获取记录
		$url = root . "control/adIndex.html?cla=" . self::page;
		foreach ($page['array'] as $k=>$array) {
			$parts = query('parts', "id = '$array[partsId]'");
            $list       = ((int)$page['para']['pageNow'] - 1) * (int)$page['para']['pageNum'] + $k + 1;
			$tr[]  = [
                componentClass::tablePperation($list,"decline(this)").
                hidden(['name' => 'mxid[]', 'value' => $array['id']]),
                $parts['code'],
                $parts['name'],
                $parts['factory'],
                $parts['model'],
                $parts['unit'],
				text(['name' => 'num', 'other' => self::digitalFiltering('numPrecision'), 'value' => self::lostZero($array['num'],'numPrecision'), 'class' => 'text', 'data' => ['id' => $array['id']], 'blur' => 'upDataMx',]),
				text(['name' => 'text', 'value' => $array['text'], 'class' => 'text', 'data' => ['id' => $array['id']], 'blur' => 'upDataMx',]),
			];
		}
		//控件
		$button = "";
		if ($this->power(self::page, "edit")) {
			$button .= spanButton([
				'cla'  => $this->get('cla'),
				'fun'  => 'addMx',
				'para' => [
					'id'   => $this->get('id'),
					'from' => 'parts',
				],
				'name' => '选择配件',
			]);
		}
		$js = <<<EOT
<script>
function addRow(){
    $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addMxEdit', $("form[name='mxForm']").serialize(), function(res) {
        if(res.warn !== 2){
            msg(res.warn)
        }else{
            window.location.href = root + "control/adIndex.html?cla=equipment&fun=detail&menu=parts&id={$this->get('id')}";
        }
    },'json');
}

function decline(that){
    let id = $(that).parent().next('[name="mxid[]"]').val()
    postData('deline', {id:id})
    $(that).parent().parent().parent().remove();
}

function upDataMx(that){
    const filed = $(that).attr('name'),
    	  id = $(that).data('id'),
    	  val = $(that).val()
    	  postData('upDataMx', {[filed]: val, id:id})
    	  
}

function postData(uri, data){
    console.log(data)
    $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun='+uri, data, function(res) {
        if(res.warn !== 2){
            msg(res.warn)
        }else{
            window.location.href = root + "control/adIndex.html?cla=equipment&fun=detail&menu=parts&id={$this->get('id')}";
        }
    },'json');
}
</script>
EOT;
		//返回
		$json['html'] =
            "<div class='tab-box'>" .
                $page['hint'] .
                "<div class='tab-button'>{$button}</div>".
                "<div class='p-10'>
                    <form name='listForm'>" . $this->tableMany(array("tr" => $tr)) . "</form>" .
                    $page['button'] .
                    $js .
                    clear .
                "</div>
            </div>";
		return json_encode($json, 320);
	}


	public function deline(): bool|string
	{
		$id = $this->post('id') ?? '';

		if (empty($id)) {
			$json['warn'] = '参数错误';
		} else {
			$where = " id = '$id' AND coid = '" . self::$coid . "' ";
			$table = 'equipment_part';
			delete([
				'table' => $table,
				'where' => $where,
			]);
			$json['warn']     = 2;
			$_SESSION['warn'] = '删除成功';
		}

		resp:
		return json_encode($json, 320);
	}

	public function upDataMx(): bool|string
	{
		$id         = $this->post('id') ?? '';
		$field      = [
			'num'  => $this->post('num'),
			'text' => $this->post('text'),
		];
		$annotation = [
			'num'  => '数量',
			'text' => '备注',
		];
		$rules      = [
			'num' => 'numeric',
		];
		// 校验是否符合规则
		$vt     = new \verify();
		$result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
		if ($result === false) {
			$json['warn'] = $vt->getErrs()[0]; // 多个规则提示最前面一条
		} else {
			$where = " id = '$id' AND coid = '" . self::$coid . "' ";
			$table = 'equipment_part';
			$info  = query($table, $where);
			if (static::isNull($info['id'])) {
				$json['warn'] = '参数错误';
			} else {
				$field        = self::filterArray($field);
				$json['warn'] = static::update([
					'table' => $table,
					'field' => $field,
					'where' => $where,
				]);

				if (in_array($json['warn'], ['新增成功', '更新成功'])) {
					$json['warn']     = 2;
					$_SESSION['warn'] = '修改成功';
				}
			}
		}

		resp:
		return json_encode($json, 320);
	}

	/**
	 * @return bool|string
	 */
	public function addMx(): bool|string
	{
		if (static::isNull($this->post('id'))) {
			return json_encode(['warn' => '参数错误', 320]);
		} else {
			$html   =
				select(["name" => "type", "title" => "类别", 'option' => explode('，', para(self::page . 'Type'))])
				. text(["name" => "code", "title" => "配件编码"])
				. text(["name" => "name", "title" => "配件名称"])
				. text(["name" => "model", "title" => "规格型号"])
				. hidden(['name' => 'eqid', 'value' => $this->post('id')]);
			$button = "<input style='margin-left: 5px' onclick=\"addRow();$('#" . self::page . "AddMx').remove()\" type='button' class='searchSub' value='提交'>";
			$html   = $this->search($html);
			return $this->layer(["title" => "添加", "height" => 600, "width" => 1100, "html" => $html, "button" => $button]);
		}
	}

	/**
	 *添加配件
	 */
	public function addMxSearch(): bool|string
	{
		$eqid  = $this->post('eqid');
		$where = " 1=1 and id not in (SELECT partsId FROM equipment_part WHERE eqid = '$eqid' )";
		$and   = " AND coid = '" . self::$coid . "' ";
		$like  = [
			'name'  => $this->post('name'),
			'code'  => $this->post('code'),
			'model' => $this->post('model'),
		];
		$equal = [
			'state' => '启用',
			'type'  => $this->post('type'),
		];
		$where .= search(["like" => $like, "=" => $equal]) . $and;
		$page  = $this->page([
			"table"   => "parts",
			"where"   => $where,
			'pageNum' => 50,
			"order"   => " `time` ASC",
		]);
		//获取表头
		$checkAll = $this->checkAll("mxForm", "mxId");
		$tr[]     = [$checkAll, '类别', '编码', '配件名称', '规格', '厂家'];
		//获取记录
		foreach ($page['array'] as $array) {
			$dominate = [
				"box" => ["name" => "mxId", "value" => $array['id']],
			];
			$tr[]     = [
				$this->dominate($dominate),
				$array['type'],
				$array['code'],
				$array['name'],
				$array['model'],
				$array['factory'],
			];
		}
		$json['html'] = $page['hint'] .
            "<form name='mxForm'>" .
                hidden(['name' => 'eqid', 'value' => $this->post('eqid')]) .
                $this->tableMany(["tr" => $tr, "showSort" => true, "page" => $page['para']]) .
            "</form>" .
            $page['button'];
		return json_encode($json, 320);
	}

	/**
	 * 编辑
	 *
	 * @return bool|string
	 */
	public function addMxEdit(): bool|string
	{
		$mxIdArr = $this->post('mxId');
		$eqid    = $this->post('eqid');
		if (!$this->power(self::page, 'edit')) {
			$json['warn'] = '你还没有编辑权限';
		} elseif (empty($mxIdArr) || !is_array($mxIdArr)) {
			$json['warn'] = '请选择配件';
		} else {
			$this->startTrans();
			$isPass = true;//事务通过标志
			$x      = 0;
			$warn   = '';
			foreach ($mxIdArr as $mxId) {
				$parts = query('parts', "id = '$mxId'");
				if (static::isNull($parts['id'])) {
					continue;
				}
				$where          = generateWhere([
					'coid'    => self::$coid,
					'eqid'    => $eqid,
					'partsId' => $mxId,
				]);
				$equipment_part = query('equipment_part', $where);
				if (static::isNull($equipment_part['id'])) {
					$warn = static::insert([
						'table' => 'equipment_part',
						'field' => [
							'id'      => self::getId(),
							'coid'    => self::$coid,
							'eqid'    => $eqid,
							'partsId' => $mxId,
							'unit'    => $parts['unit'],
							'stid'    => self::$stid,
						],
					]);
				} else {
					$warn = static::update([
						'table' => 'equipment_part',
						'field' => [
							'eqid'    => $eqid,
							'partsId' => $mxId,
							'unit'    => $parts['unit'],
							'stid'    => self::$stid,
						],
						'where' => $where,
					]);
				}
				if (!in_array($warn, ["新增成功", "更新成功"])) {
					$isPass = false;
					break;
				} else {
					$x++;
				}
			}
			if ($isPass !== true) {
				$this->rollback();
			} else {
				$this->commitTrans();
				//添加日志
				$type = mb_substr($warn, 0, 2, 'utf-8');
				$text = $this->control['name'] . $type . "了{$x}条设备配件， 设备id：【" . $eqid . '】';
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $warn;
				$json['warn']     = 2;
			}
		}
		return json_encode($json, 320);
	}


	/**
	 * 编辑页
	 *
	 * @return string
	 */
    public function edit()
    {
        $id       = $this->post('id');
        $info     = query(self::table, " coid = '" . self::$coid . "' AND id = '" . $id . "' ");
        //表单
        $html = $this->layerEdit([
            "table" => [
                [
                    must . '配件名称' => text(['name' => "name", 'class' => 'text', 'value' => $info['name']]),
                    must . '类别' => select(['name' => "type", 'class' => 'text', 'value' => $info['type'], 'option' => explode('，', para(self::page . 'Type'))]),
                ],
                [
                    '厂家' => text(['name' => "factory", 'class' => 'text', 'value' => $info['factory']]),
                    must . '规格' => text(['name' => "model", 'class' => 'text', 'value' => $info['model']]),
                ],
                [
                    must . '计量单位' => select(['name' => "unit", 'class' => 'text', 'value' => $info['unit'], 'option' => explode('，', para(self::page . 'Unit'))]),
                    '参考单价' => text(['name' => "price", 'class' => 'text', 'value' => $info['price'], 'unit' => static::$unit]),
                ],
                [
                    '备注' => textarea(['name' => "text", 'class' => 'text', 'value' => $info['text']]),
                ],

            ],
            'hidden' => hidden(['name' => 'id', 'value' => $id]),
        ]);
        //返回
        return $this->layer(array("title" => L('job.button.editor').self::title, "height" => 350, "html" => $html));
    }

	/**
	 * 编辑报错
	 *
	 * @return bool|string
	 */
	public function editEdit(): bool|string
	{
		$id         = $this->post('id') ?: self::getId();
		$field      = [
			// 'code'    => $this->post('code'),
			'name'    => $this->post('name'),
			'type'    => $this->post('type'),
			'model'   => $this->post('model'),
			'factory' => $this->post('factory'),
			'unit'    => $this->post('unit'),
			'price'   => $this->post('price'),
			'text'    => $this->post('text'),
			'state'   => $this->post('state'),
		];
		$annotation = [
			// 'code'    => '编码',
			'name'    => '名称',
			'type'    => '类型',
			'model'   => '规格型号',
			'factory' => '厂家',
			'unit'    => '单位',
			'price'   => '价格',
			'text'    => '备注',
			'state'   => '状态',
		];
		$rules      = [
			// 'code'  => 'required',
			'name'  => 'required',
			'type'  => 'required',
			'model' => 'required',
			// 'factory' => 'required',
			'unit'  => 'required',
			// 'price'   => 'required',
			// 'text'    => 'required',
		];
		// 校验是否符合规则
		$vt     = new \verify();
		$result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
		if ($result === false) {
			$json['warn'] = $vt->getErrs()[0]; // 多个规则提示最前面一条
			goto resp;
		}
		$where = " id = '$id' ";
		$info  = query(self::table, $where);
		//判断
		if (!$this->power(self::page, "edit")) {
			$json['warn'] = "你没有编辑" . self::title . "的权限";
		} else {
			$this->startTrans();
			$isPass = true;//事务通过标志
			if (!$info['id']) {
				$orderNo      = codeTemplateClass::generateCode(self::page,[
                    'prefix' => 'OS',
                    // 'prefix' => 'OS' . date('Ymd'),
                    'table'  => self::table,
                    'field'  => 'code',
                    'where'  => " AND coid = '" . self::$coid . "' ",
                ],$field);
				$field        = array_merge($field, [
					'id'    => $id,
					'code'  => $orderNo,
					'state' => '启用',
					'coid'  => self::$coid,
					'stid'  => $this->control['stid'],
				]);
				$json['warn'] = static::insert(["table" => self::table, "field" => $field]);
			} else {
				$json['warn'] = static::update([
					"table" => self::table,
					"field" => $field,
					"where" => $where,
				]);
			}
			if (in_array($json['warn'], ["新增成功", "更新成功"]) && $isPass) {
				$this->commitTrans();
				//添加日志
				$type = mb_substr($json['warn'], 0, 2, 'utf-8');
				$text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$_SESSION['warn'] = $json['warn'];
				$json['warn']     = 2;
				$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
			} else {
				$this->rollback();
			}
		}

		resp:
		return json_encode($json, 320);
	}

	/*详情页*/
	public function detail(): string
	{
		$info = query(self::table, " coid = '" . self::$coid . "' AND id = '{$this->get('id')}'");
		if (empty($info['id'])) {
			$html = '未找到此' . self::title;
		} else {
			//菜单
			$data   = array(
				"id" => $info['id'],
			);
			$button = [];
			if ($this->power(self::page, "edit")) {
				//按钮
				$button[] = [
					"name" => "删除",
					"type" => "弹出层",
					"cla"  => $this->get('cla'),
					"fun"  => "operate",
					"post" => ["act" => 'del', "id" => $info['id']],
				];
				$button[] = [
					"name"  => "编辑",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "edit",
                    "post" => ["id" => $info['id']],
					'style' => 'li-btn-blue-bg',
				];
			}
			//生成表单
            $data['button'] = $this->tableShowButton($button);
			$data['html'] = $this->tableShow([
				[
					[
						"配件名称" => $info['name'],
						"类别"   => $info['type'],
						"规格"   => $info['model'],
                        "厂家"      => $info['factory'],
					],
					[
						"计量单位"    => $info['unit'],
						"参考单价（".static::$unit."）" => $info['price'],
					],
					[
						"备注" => pre($info['text'])
					],
				],
				'状态'     => [
					[
						"编码"   => $info['code'],
						"创建人"  => self::findStaff($info['stid']),
						"创建时间" => $info['time'],
                        "更新时间" => $info['updateTime'],
					],
					[
						"状态" => $info['state'],
					],
				],
			]);
			//生成页面
			$html = $this->tab($data);
		}
		//返回
		return $html;
	}

	// 操作中转
	public function operate(): bool|string
	{
		$act    = $this->post('act') ?? '';
		$pwd    = $word = false; // 需要密码
		$append = [];
		switch ($act) {
			case 'changeState':
				$act      = 'state';
				$msg      = self::title . '修改状态';
				$title    = self::table . 'Change';
				$function = 'changeState';
				$form     = 'userOperateForm, listForm';
				if ($this->post('state')) {
					$append = [
						0 => hidden(['name' => 'state', 'value' => $this->post('state')]),
					];
				}
				$power = '';
				break;
			default:
				$act      = 'del';
				$msg      = '删除' . self::title;
				$title    = self::page . 'Delete';
				$function = 'delete';
				$form     = self::page . 'OperateForm, listForm, quoForm';
				$power    = '';
				break;
		}
		if (!$this->power(self::page, $act)) {
			$_SESSION['warn'] = '你还没有' . $msg . '的权限';
			$json             = [
				'warn' => 2,
				'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
			];
		} else {
			return $this->confirm([
				'title'    => $title,
				'function' => $function,
				'form'     => $form,
				'power'    => $power,
				'pwd'      => $pwd,
				'word'     => $word,
				'append'   => $append,
			]);
		}

		resp:
		return json_encode($json, 320);
	}

	/**
	 * 修改状态
	 *
	 * @return bool|string
	 */
	public function changeState(): bool|string
	{
		$array = $this->post('listId') ?? $this->post('id');
		$state = $this->post('state') ?: '停用';
		$act   = 'state';
		$json  = [];
		if (!$this->power(self::page, $act)) {
			$json['warn'] = "你没有此权限的权限";
		} elseif (empty($array)) {
			$json['warn'] = "你一条记录都没有选择呢";
		} else {
			$text  = '';
			$x     = 0;
			$array = is_array($array) ? $array : [$array];
			// 修改field
			$fieldKey = 'state';
			foreach ($array as $id) {
				$where = " id = '$id' ";
				$info  = query(self::table, $where);
				if (static::isNull($info['id']) || $info['state'] == $state) {
					continue;
				}
				$fieldVlaue = ($info['state'] === '启用') ? '停用' : '启用';
				// 修改状态
				static::update([
					"table" => self::table,
					'field' => [
						$fieldKey => $fieldVlaue,
					],
					"where" => $where,
				]);
				//添加记录
				$text .= "管理员{$this->control['name']}修改了一条" . self::title . "：ID【{$id}】<br>";
				$x++;
			}
			// 写入日志
			$this->logText(["type" => self::page, "text" => $text]);
			$_SESSION['warn'] = "修改了{$x}条" . self::title;
			$json['warn']     = 2;
			$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
		}
		resp:
		return json_encode($json, 320);
	}

	/**
	 * 删除
	 *
	 * @return bool|string
	 */
	public function delete(): bool|string
	{
		$array = $this->post('listId') ?? $this->post('id');
		if (!$this->power(self::page, "del")) {
			$json['warn'] = "你没有删除的权限";
		} elseif (empty($array)) {
			$json['warn'] = "你一个数据都没有选择呢";
		} else {
			$text  = "";
			$x     = 0;
			$array = is_array($array) ? $array : [$array];
			foreach ($array as $id) {
				$info = query(self::table, " coid = '" . self::$coid . "' AND id = '$id' ");
				if ($info['state'] == '已确认') {
					$warn = "删除失败：已确认，暂不能删除";
				} else {
					//最后删除基本参数
					delete(array("table" => self::table, "where" => " id = '$id' "));
					delete(array("table" => 'auditing_follow', "where" => " typeId = '$id' "));
					//返回
					$warn = "删除成功";
					$x++;
				}
				$text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
			}
			//添加日志
			$text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
			$this->logText(array("type" => self::page, "text" => $text));
			$_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
			$json['warn']     = 2;
			$json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
		}
		return json_encode($json, 320);
	}


	/**
	 * 下载模板
	 */
	public function downloadModel()
	{

        $templateId = $this->get('templateId');
		if (!$this->power(self::page, 'import')) {
			$_SESSION['warn'] = '你还没有导入的权限';
        } else {
            $exampleData[] = [
				'配件类别一', 'OS0001', '配件名称', '厂家名称', '规格', '单位一', '12',
				'(样例数据，导入时请删除本条数据)',
			];

            $excel    = $this->excelHead();
            $fileName = self::title.'导入模板-'.importTemplateClass::getName($templateId).'.xlsx';
            $filePath = $excel->fileName($fileName, 'sheet1');
            $format = new \Vtiful\Kernel\Format($filePath->getHandle());
            $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
            $index         = 0;
            foreach ($templateField as $k => $array) {
                if ($array['display']){
                    $backgroundStyle=null;
                    if (importTemplateClass::getIsMustValue($this->importFieldInit(), $array['columnName'])){
                        //必填项判断
                        $backgroundStyle  = $format->background(
                            0xFFC04B
                        )->toResource();
                    }
                    $filePath->insertText(0, $index, $array['aliasName'],'',$backgroundStyle);
                    foreach ($exampleData as $y=>$example){
                        $exampleVal = match ($array['columnName']){
                            '类别'=>$example[0],
                            '编码'=>$example[1],
                            '配件名称'=>$example[2],
                            '厂家'=>$example[3],
                            '规格'=>$example[4],
                            '计量单位'=>$example[5],
                            '单价'=>$example[6],
                            default=>'',
                        };
                        $filePath->insertText($y+1, $index, $exampleVal);
                    }
                    $index++;
                }
            }
			$text   = $this->control['name'] . "下载了" . self::title . "导入模板";
			$this->logText(["type" => self::page, "text" => $text]);
            $this->excelOutPut($filePath,$fileName);
			exit(0);
		}
		header("Location:" . getenv("HTTP_REFERER"));
	}


	/*数据导入*/
	public function importData()
	{
        $templateId = $this->post('templateId');
		if (!$this->power(self::page, 'import')) {
			$json['warn'] = '你还没有导入的权限';
        }  else {
			 $fomatArray = [];//导入数据格式同一为TYPE_STRING
            foreach ($this->importFieldInit() as $value){
                $fomatArray[] = \Vtiful\Kernel\Excel::TYPE_STRING;
            }
            $data = $this->importHead(format: $fomatArray);
			$x    = 0;
			$text = '';
            $headArray = [];
            $row_list=0;
            foreach ($data as $i => $row) {
                $row_list++;
                if ($i==0){
                    $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
                    $headArray = importTemplateClass::combinHead($templateField,$row);
                }
				if ($i > 0) {
                    $rowData = formSubArray($row);
                    //只接收模板中选中的字段的值
                    $item = [];
                    foreach ($headArray as $index=>$headName){
                        $item[$headName] = $rowData[$index]??'';
                    }
                    //初始化未被模板需要的字段的值
                    foreach ($this->importFieldInit() as $value){
                        $item[$value['columnName']] = $item[$value['columnName']]??'';
                    }
					$field      = [
						'code'    => $item['编码'],
						'name'    => $item['配件名称'],
						'type'    => $item['类别'],
						'model'   => $item['规格'],
						'factory' => $item['厂家'],
						'unit'    => $item['计量单位'],
						'price'   => $item['单价'],
					];
					$annotation = [
						'code'    => '编码',
						'name'    => '名称',
						'type'    => '类型',
						'model'   => '规格型号',
						'factory' => '厂家',
						'unit'    => '单位',
						'price'   => '价格',
						'text'    => '备注',
						'state'   => '状态',
					];
					$rules      = [
						'code'  => 'required',
						'name'  => 'required',
						'type'  => 'required',
						'model' => 'required',
						'unit'  => 'required',
					];
					// 校验是否符合规则
					$vt     = new \verify();
					$result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
					if ($result === false) {
						$text .= "\n第【{$row_list}】行，" . $vt->getErrs()[0];
					} else {
						$where = generateWhere([
							'coid'  => self::$coid,
							'type'  => $field['type'],
							'code'  => $field['code'],
							'name'  => $field['name'],
							'model' => $field['model'],
						]);
						$info  = query(self::table, $where);
						// 新增
						if (static::isNull($info['id'])) {
							$orderNo = codeTemplateClass::generateCode(self::page,[
                                'prefix' => 'OS',
                                'table'  => self::table,
                                'field'  => 'code',
                                'where'  => " AND coid = '" . self::$coid . "' ",
                            ],$field);
							$field   = array_merge($field, [
								'id'    => self::getNo(),
								'code'  => $orderNo,
								'state' => '启用',
								'coid'  => self::$coid,
								'stid'  => $this->control['stid'],
							]);
							$warn    = static::insert([
								"table" => self::table,
								"field" => $field,
							]);
						} else {
							$warn = static::update([
								"table" => self::table,
								"field" => $field,
								'where' => $where,
							]);
						}
						if (in_array($warn, ["新增成功", "更新成功"])) {
							$x++;
                            $text .= "第【{$row_list}】行数据导入成功<br>";
                        } else {
                            $text .= "第【{$row_list}】行导入失败：编辑失败<br>";
                        }
					}
				}
			}
            $total = count($data)-1;
            $json['data'] = [
                'text'=>$text,
                'title'=>"您导入了{$total}条数据，成功{$x}条，失败".($total-$x)."条",
            ];
			$text = $this->control['name'] . '导入了文件：' . $_FILES['file']['name'] . '：' . $text;
			$this->logText(["type" => self::page, "text" => $text]);
            $json['warn'] = 2;
        }
        return json_encode($json,320);
	}

	/**
	 * 导出
	 */
	public function exportData()
	{
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        }  else {
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    "table" => self::table,
                    "where" => "id in ('".implode("','", $checkedId)."') order by time desc",
                ))['array'];
            }else{
                $sql   = $_SESSION[self::page]['sql'];
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                $inventoryNum = self::inventoryNum($array['id']);
                $unitPrice    = self::unitPrice($array['id']);
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '类别'=>$array['type'],
                            '编码'=>$array['code'],
                            '配件名称'=>$array['name'],
                            '厂家'=>$array['factory'],
                            '规格'=>$array['model'],
                            '计量单位'=>$array['unit'],
                            '数量'=>self::lostZero($inventoryNum,'numPrecision'),
                            '单价'=>self::lostZero($unitPrice,'pricePrecision'),
                            '金额'=> self::formattingFigure($unitPrice * $inventoryNum),
                            '状态'=>$array['state'],
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }
			$text = $this->control['name'] . "导出了配件信息";
			$this->logText(["type" => self::page, "text" => $text]);
			$this->excelOut($title, $data, "配件信息.xlsx");
            exit(0);
		}
		header("Location:" . getenv("HTTP_REFERER"));

	}


	/**
	 * 库存单价
	 *
	 * @param string $partsId
	 * @return float
	 */
	public static function unitPrice(string $partsId): float
	{
		return round(static::total([
			'sql'   => "SELECT IFNULL(SUM(d.money)/sum(d.num), 0) as total FROM `parts_inventory_detail` as d, parts_inventory as i WHERE d.orderId = i.id AND i.classify = 1 ",
			'where' => [
				'd.partsId' => $partsId,
				'd.coid'    => self::$coid,
			],
		]), 2);
	}

	/**
	 * 库存数量
	 *
	 * @param string $partsId
	 * @param string $warehouseId
	 * @return float
	 */
	public static function inventoryNum(string $partsId, string $warehouseId = ''): float
	{
		$where = [
			'partsId' => $partsId,
			'coid'    => self::$coid,
		];
		if ($warehouseId) {
			$where['warehouseId'] = $warehouseId;
		}
		return static::total([
			'sql'   => 'SELECT IFNULL(sum(num), 0) as total FROM `parts_inventory_record`',
			'where' => $where,
		]);
	}

    /**
     * 导入模板字段初始化
     * @return array[]
     */
    public function importFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'类别',
                    'aliasName'=>'类别',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'编码',
                    'aliasName'=>'编码',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'配件名称',
                    'aliasName'=>'配件名称',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'厂家',
                    'aliasName'=>'厂家',

                    'isMust'=>false,
                ],
                [
                    'columnName'=>'规格',
                    'aliasName'=>'规格',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'计量单位',
                    'aliasName'=>'计量单位',

                    'isMust'=>true,
                ],
                [
                    'columnName'=>'单价',
                    'aliasName'=>'单价',

                    'isMust'=>false,
                ],
            ]
        };
    }

    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'类别',
                    'aliasName'=>'类别',
                ],
                [
                    'columnName'=>'编码',
                    'aliasName'=>'编码',
                ],
                [
                    'columnName'=>'配件名称',
                    'aliasName'=>'配件名称',
                ],
                [
                    'columnName'=>'厂家',
                    'aliasName'=>'厂家',
                ],
                [
                    'columnName'=>'规格',
                    'aliasName'=>'规格',
                ],
                [
                    'columnName'=>'计量单位',
                    'aliasName'=>'计量单位',
                ],
                [
                    'columnName'=>'数量',
                    'aliasName'=>'数量',
                ],
                [
                    'columnName'=>'单价',
                    'aliasName'=>'单价（元）',
                ],
                [
                    'columnName'=>'金额',
                    'aliasName'=>'金额（元）',
                ],
                [
                    'columnName'=>'状态',
                    'aliasName'=>'状态',
                ],
            ]
        };
    }
}
